package com.example.demo.config;

import com.example.demo.pojo.User;
import com.example.demo.service.UserService;
import com.example.demo.utils.Md5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权==>AuthorizationInfo");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //获取认证处的user，即当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        //设置当前用户的权限
        info.addStringPermission(user.getPower());
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证==>AuthenticationInfo");

//        //用户名，密码，数据库取
//        String name = "root";
//        String password = "123456";
//
//        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
//        if (!userToken.getUsername().equals(name)) {
//            return null;    //抛出异常  UnknownAccountException
//        }

        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        //链接数据库
        User user = userService.selectByName(userToken.getUsername());
        if (user==null){
            return null;
        }

        //登录成功返回一个session，放在这里不太好，密码未验证
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser",user);

        //密码认证，shiro做  //此处的user【第一个参数】可以被授权处获得
        return new SimpleAuthenticationInfo(user, user.getPasswd(),"");
    }
}
